//
//  fetchViewController.m
//  BackgroundTaskSample
//  后台获取
//  在用户打开app之前能有机会执行代码获取数据并更新UI，这样在用户打开app的时候展示的是最新的信息
//  1.Capabilities开启后台获取
//  2.设置获取间隔
//  3.实现-application:performFetchWithCompletionHandler更新UI并通知系统
//
//  Created by moliya on 16/4/23.
//  Copyright © 2016年 Wanquan Network Technology. All rights reserved.
//

#import "fetchViewController.h"
#import "executeDateTableViewCell.h"

@interface fetchViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *executeDateTableView;
@property (strong, nonatomic) NSMutableArray *dateArray;

@end

@implementation fetchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _dateArray = [NSMutableArray array];
    //读取记录
    NSArray *executeDateArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"ExecuteDate"];
    if (executeDateArray) {
        [_dateArray addObjectsFromArray:executeDateArray];
    }
    //注册cell，如果storyboard已添加Cell并设置了ReuseIdentifier则不调用
    //[_executeDateTableView registerClass:[executeDateTableViewCell class] forCellReuseIdentifier:@"executeDateCell"];
    
    //添加清空item
    UIBarButtonItem *trashItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(removeData)];
    self.navigationItem.rightBarButtonItem = trashItem;
    //添加时间间隔选择item
    UISegmentedControl *fetchIntervalSegment = [[UISegmentedControl alloc] initWithItems:@[@"最短", @"15分钟", @"1小时"]];
    [fetchIntervalSegment setFrame:CGRectMake(0, 0, 80, 30)];
    [fetchIntervalSegment addTarget:self action:@selector(changeFetchTime:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = fetchIntervalSegment;
}

#pragma mark fetchData 获取数据
- (void)fetchDataWithCompletionHandler:(void (^)(CFBackgroundUpdateResult))completionHandler {
    //执行获取任务
    NSLog(@"后台获取执行中");
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSMutableString *titleString = [NSMutableString stringWithString:[dateFormatter stringFromDate:[NSDate date]]];
    [UIApplication sharedApplication].applicationIconBadgeNumber += 1;
    NSUInteger result = arc4random() % 3;
    switch (result) {
        case 0:
            NSLog(@"0");
            [titleString appendString:@" NewData"];
            completionHandler(CFBackgroundUpdateResultNewData);
            break;
        case 1:
            NSLog(@"1");
            [titleString appendString:@" NoData"];
            completionHandler(CFBackgroundUpdateResultNoData);
            break;
        case 2:
            NSLog(@"2");
            [titleString appendString:@" Failed"];
            completionHandler(CFBackgroundUpdateResultFailed);
            break;
        default:
            break;
    }
    
    [_dateArray insertObject:titleString atIndex:0];
    [[NSUserDefaults standardUserDefaults] setObject:_dateArray forKey:@"ExecuteDate"];
    
    //更新tableView
    [_executeDateTableView reloadData];
}

#pragma mark - TableView delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dateArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    executeDateTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"executeDateCell" forIndexPath:indexPath];
    cell.dateLabel.text = _dateArray[indexPath.row];
    
    return cell;
}

#pragma mark - 选择获取的间隔时间
- (void)changeFetchTime:(UISegmentedControl *)sender {
    NSUInteger index = sender.selectedSegmentIndex;
    
    NSUInteger interval = UIApplicationBackgroundFetchIntervalMinimum;
    switch (index) {
        case 0:
            interval = UIApplicationBackgroundFetchIntervalMinimum;
            break;
        case 1:
            interval = 15 * 60;
            break;
        case 2:
            interval = 60 * 60;
            break;
        default:
            break;
    }
    [[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:interval];
    NSLog(@"选择了时间间隔%@", @(interval));
}

#pragma mark - 清空数据
- (void)removeData {
    [_dateArray removeAllObjects];
    [_executeDateTableView reloadData];
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"ExecuteDate"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
